package com.sna.snaapplication.controller.Load;
import com.sna.snaapplication.entity.File.FileHistoryEntity;
import com.sna.snaapplication.entity.File.export.ExportRequest;
import com.sna.snaapplication.entity.File.export.ExportResult;
import com.sna.snaapplication.entity.File.FileEntity;
import com.sna.snaapplication.entity.File.FileInfoDTO;
import com.sna.snaapplication.entity.R;
import com.sna.snaapplication.entity.usercore.User;
import com.sna.snaapplication.mapper.UserMapper;
import com.sna.snaapplication.service.File.FileHistoryService;
import com.sna.snaapplication.service.File.FileService;
import com.sna.snaapplication.utils.AliOssUtil;
import com.sna.snaapplication.utils.CurrentLoginUtil;
import com.sna.snaapplication.utils.ThreadLocalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/files")
public class FileLoadController {

    private static final Logger logger = LoggerFactory.getLogger(FileLoadController.class);

    @Autowired
    private FileService fileService;

    @Autowired
    private FileHistoryService fileHistoryService;

    @Autowired
    CurrentLoginUtil currentLoginUtil;

    @Autowired
    private UserMapper userMapper;

    // 导出 - 修改为GET请求
    @GetMapping("/exportCzml")
    public ResponseEntity<R> exportCzml(@RequestParam("file_id") Long fileId,
                                        @RequestParam("filename") String filename) throws Exception {
        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("username");
        User user = userMapper.findByUserName(userName);

        // 根据文件ID获取文件信息
        FileEntity file = fileService.getFileById(fileId);
        if (file == null) {
            return ResponseEntity.badRequest().body(R.fail("文件不存在"));
        }

        // 获取文件的OSS URL
        String url = file.getStoragePath();

        // 记录历史
        FileHistoryEntity fileHistory = new FileHistoryEntity();
        fileHistory.setFileId(fileId);
        fileHistory.setUserId(user.getUserId());
        fileHistory.setActionTime(LocalDateTime.now());
        fileHistory.setAction("Export");
        fileHistoryService.save(fileHistory);

        // 返回成功响应
        return ResponseEntity.ok(R.ok(url));
    }

    // 导入
    @PostMapping("/importCzml")
    public ResponseEntity<R> importCzml(@RequestParam("file") MultipartFile file) throws Exception {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(R.fail("错误：未提供文件"));
        }

        // 2. 检查文件类型是否是 CZML
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.toLowerCase().endsWith(".czml")) {
            return ResponseEntity.badRequest().body(R.fail("仅支持 czml 文件上传"));
        }

        try {
            // 获取当前用户id
            Map<String, Object> map = ThreadLocalUtil.get();
            String userName = (String) map.get("username");
            User user = userMapper.findByUserName(userName);

            // 3. 检查是否存在同名文件
            FileEntity existingFile = fileService.getFileByNameAndUserId(filename, user.getUserId());
            if (existingFile != null) {
                // 删除已存在的文件
                logger.info("发现同名文件，准备删除旧文件: {}", filename);

                // 从阿里云OSS删除旧文件
                boolean ossDeleteSuccess = AliOssUtil.deleteFile(existingFile.getName());
                if (!ossDeleteSuccess) {
                    logger.warn("删除旧OSS文件失败: {}", existingFile.getName());
                }

                // 从数据库删除旧文件记录
                boolean dbDeleteSuccess = fileService.removeById(existingFile.getId());
                if (!dbDeleteSuccess) {
                    logger.warn("删除旧数据库记录失败: {}", existingFile.getId());
                }
            }

            // 4. 获取czml文件内容
            byte[] bytes = file.getBytes();

            // 5. 上传到阿里云OSS
            String url = AliOssUtil.uploadFile(filename, bytes);

            // 6. 记录文件记录
            FileEntity importfile = new FileEntity();
            importfile.setName(filename);
            importfile.setStoragePath(url);
            importfile.setFileType("czml");
            importfile.setSize((long) bytes.length);
            importfile.setUserId(user.getUserId());

            // 保存文件记录到数据库
            fileService.save(importfile);

            // 历史记录
            FileHistoryEntity fileHistory = new FileHistoryEntity();
            fileHistory.setFileId(importfile.getId());
            fileHistory.setUserId(user.getUserId());
            fileHistory.setActionTime(LocalDateTime.now());
            fileHistory.setAction("Import");

            // 保存历史记录到数据库
            fileHistoryService.save(fileHistory);

            String message = existingFile != null ? "文件已更新" : "文件导入成功";
            return ResponseEntity.ok(R.ok(message));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(R.fail("错误：文件导入失败，原因： " + e.getMessage()));
        }
    }

    // 查询该用户账号下所有文件名字以及id
    @GetMapping("/queryCzml")
    public ResponseEntity<R> queryCzml() {
        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("username");
        User user = userMapper.findByUserName(userName);

        // 查询用户的所有文件
        List<FileInfoDTO> files = fileService.getUserFiles(user.getUserId());

        return ResponseEntity.ok(R.ok(files));
    }

    // 删除文件
    @DeleteMapping("/deleteCzml")
    public ResponseEntity<R> deleteCzml(@RequestParam("file_id") Long fileId) {
        try {
            // 获取当前用户id
            Map<String, Object> map = ThreadLocalUtil.get();
            String userName = (String) map.get("username");
            User user = userMapper.findByUserName(userName);

            // 根据文件ID获取文件信息
            FileEntity file = fileService.getFileById(fileId);
            if (file == null) {
                return ResponseEntity.badRequest().body(R.fail("文件不存在"));
            }

            // 验证文件是否属于当前用户
            if (!file.getUserId().equals(user.getUserId())) {
                return ResponseEntity.badRequest().body(R.fail("无权删除此文件"));
            }

            // 从阿里云OSS删除文件
            String ossUrl = file.getStoragePath();
            String fileName = file.getName();
            boolean deleteSuccess = AliOssUtil.deleteFile(fileName);

            if (!deleteSuccess) {
                return ResponseEntity.badRequest().body(R.fail("OSS文件删除失败"));
            }

            // 删除数据库中的文件记录
            boolean dbDeleteSuccess = fileService.removeById(fileId);
            if (!dbDeleteSuccess) {
                return ResponseEntity.badRequest().body(R.fail("数据库记录删除失败"));
            }

            //这段代码报错，错误我没看，注释掉看是不是可以用，可以用就不记录了
//            // 记录删除操作历史
//            FileHistoryEntity fileHistory = new FileHistoryEntity();
//            fileHistory.setFileId(fileId);
//            fileHistory.setUserId(user.getUserId());
//            fileHistory.setActionTime(LocalDateTime.now());
//            fileHistory.setAction("Delete");
//            fileHistoryService.save(fileHistory);

            return ResponseEntity.ok(R.ok("文件删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(R.fail("文件删除失败：" + e.getMessage()));
        }
    }
}